import socket
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import os
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
address = ('127.0.0.1', 2345)
server_socket.bind(address)
server_socket.listen()
print('服务器正在监听 {}'.format(address))
client_socket, addr = server_socket.accept()
# 接收客户端发送的 AES 密钥
key = client_socket.recv(32)
print("已接收客户端密钥")
def encrypt_message(message):
    iv = os.urandom(AES.block_size)  # 随机生成 IV
    cipher = AES.new(key, AES.MODE_CBC, iv)
    encrypted = cipher.encrypt(pad(message.encode('utf-8'), AES.block_size))
    return iv + encrypted  # 返回 IV + 密文
def decrypt_message(encrypted_data):
    iv = encrypted_data[:AES.block_size]  # 提取 IV
    ciphertext = encrypted_data[AES.block_size:]  # 提取密文
    cipher = AES.new(key, AES.MODE_CBC, iv)
    decrypted = unpad(cipher.decrypt(ciphertext), AES.block_size)
    return decrypted.decode('utf-8')
try:
    while True:
        # 接收客户端消息并解密
        encrypted_data = client_socket.recv(1024)
        if not encrypted_data:
            break
        decrypted_msg = decrypt_message(encrypted_data)
        print(f"客户端说: {decrypted_msg}")
        # 发送加密回复
        reply = input("输入回复消息: ")
        encrypted_reply = encrypt_message(reply)
        client_socket.send(encrypted_reply)
except Exception as e:
    print(f"发生错误: {e}")
finally:
    client_socket.close()
    server_socket.close()
    print("服务器已关闭")